package com.example.contactapp;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

import android.view.View;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import android.widget.ListView;


import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;



public class MainActivity2 extends AppCompatActivity {
    private ListView contactListView;
    private ContactAdapter adapter;
    private DatabaseHelper dbHelper;
    private ImageView img;
    private int userId;
    private TextView stickyHeader;
    private List<Contact> contacts;
    private SideIndexView sideIndexView;
    private SearchView searchView;
    private List<Contact> originalContacts;

    private static final int REQUEST_CODE_CONTACT_DETAILS = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        dbHelper = new DatabaseHelper(this);

        Intent intent = getIntent();
        String username = intent.getStringExtra("username");

        contactListView = findViewById(R.id.contactListView);
        stickyHeader = findViewById(R.id.stickyHeader);
        sideIndexView = findViewById(R.id.sideIndexView);
        searchView = findViewById(R.id.searchView);



        contactListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Contact selectedContact = (Contact) adapterView.getItemAtPosition(i);

                // 创建 Intent 并传递选中的 Contact 对象
                Intent intent1 = new Intent(MainActivity2.this, MainActivity3.class);
                intent1.putExtra("selectedContact", (Serializable) selectedContact);
                startActivity(intent1);
            }
        });

        if (username != null) {
            userId = getUserIdByUsername(username);
            if (userId != -1) {
                 contacts = dbHelper.getContactsByUserId(userId);
                originalContacts = new ArrayList<>(contacts);
                 Collections.sort(contacts);//排序
                //  contacts 是从数据库获取的联系人列表
                adapter = new ContactAdapter(contacts, this,stickyHeader);

                contactListView.setAdapter(adapter); // 确保这一行正确
            } else {
                Toast.makeText(this, "用户不存在", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "用户名为空", Toast.LENGTH_SHORT).show();
        }

        //添加滚动监听器以实现首字母吸顶效果
        contactListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // 不需要处理滚动状态变化
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem < contacts.size()) {
                    adapter.updateStickyHeader(firstVisibleItem);
                }
            }
        });

        // 实现侧边栏字母索引

        sideIndexView.setOnTouchIndexListener(index -> {
            int position = getPositionByIndex(index);
            if (position >= 0 && position < contacts.size()) {
                contactListView.setSelection(position);
            }
        });
        // 实现快速搜索
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                filterContacts(newText);
                return true;
            }
        });

        //为添加图片加上监听事件
        img = (ImageView) findViewById(R.id.add);
        img.setOnClickListener(view -> {
            showAddDialog();
        });

    }


    @SuppressLint("Range")
    private int getUserIdByUsername(String username) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        String[] columns = {DatabaseHelper.COLUMN_USER_ID};
        String selection = DatabaseHelper.COLUMN_USERNAME + " = ?";
        String[] selectionArgs = {username};

        Cursor cursor = db.query(DatabaseHelper.TABLE_USER, columns, selection, selectionArgs, null, null, null);

        int userId = -1;
        if (cursor.moveToFirst()) {
            userId = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN_USER_ID));
        }

        cursor.close();
        db.close();

        return userId;
    }

    private void showAddDialog() {
        // 创建一个新的 Dialog
        Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.dialog_add_layout);

        // 获取 Dialog 中的控件
        EditText editTextName = dialog.findViewById(R.id.edit_text_name);
        EditText editTextAddress = dialog.findViewById(R.id.edit_text_address);
        EditText editTextPhone = dialog.findViewById(R.id.edit_text_phone);
        EditText editTextAge = dialog.findViewById(R.id.edit_text_age);
        EditText editTextInterests = dialog.findViewById(R.id.edit_text_interests);
        Button buttonCancel = dialog.findViewById(R.id.button_cancel);
        Button buttonSave = dialog.findViewById(R.id.button_save);

        //动态调整
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(dialog.getWindow().getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT; // 宽度匹配父容器
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT; // 高度根据内容自动调整
        dialog.getWindow().setAttributes(lp);

        // 设置取消按钮的点击事件
        buttonCancel.setOnClickListener(v -> {
            // 关闭 Dialog
            dialog.dismiss();

        });

        // 设置保存按钮的点击事件
        buttonSave.setOnClickListener(v -> {

            // 获取输入的值
            String name = editTextName.getText().toString();
            String address = editTextAddress.getText().toString();
            String phone = editTextPhone.getText().toString();
            int age = Integer.parseInt(editTextAge.getText().toString());
            String interests = editTextInterests.getText().toString();

//             处理保存逻辑
            saveContact(name, address, phone, age, interests,userId);

            // 关闭 Dialog
            dialog.dismiss();
            //刷新页面
            refreshPage();

        });

        // 显示 Dialog
        dialog.show();
    }

    private void saveContact(String name,String address,String phone,int age,String interests,int userid){
        long id;
        try (DatabaseHelper dbHelper = new DatabaseHelper(this)) {
            id = dbHelper.insertContact(name, address, phone, age, interests, userid);
        }

        if (id != -1){
            Toast.makeText(MainActivity2.this,"添加成功",Toast.LENGTH_SHORT).show();

        }else {
            Toast.makeText(MainActivity2.this,"添加失败",Toast.LENGTH_SHORT).show();
        }

    }

    public void refreshPage() {
        loadContacts();
        adapter.notifyDataSetChanged(); // 通知适配器数据已更改
    }

    private void loadContacts() {
        List<Contact> contacts = dbHelper.getContactsByUserId(userId);
        Collections.sort(contacts);//排序
        adapter = new ContactAdapter(contacts, this,stickyHeader);
        contactListView.setAdapter(adapter);
    }

    private int getPositionByIndex(String index) {
        for (int i = 0; i < contacts.size(); i++) {
            if (Character.toString(contacts.get(i).getFirstLetter()).equals(index)) {
                return i;
            }
        }
        return -1;
    }

    private void filterContacts(String query) {
        List<Contact> filteredContacts = new ArrayList<>();
        for (Contact contact : originalContacts) {
            if (contact.getName().toLowerCase().contains(query.toLowerCase())) {
                filteredContacts.add(contact);
            }
        }
        contacts.clear();
        contacts.addAll(filteredContacts);
        adapter.notifyDataSetChanged();
    }

}